import { fileURLToPath, URL } from "node:url";
import path from "path";

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { createHtmlPlugin } from "vite-plugin-html";
import { visualizer } from "rollup-plugin-visualizer";

import viteCompression from "vite-plugin-compression";
import VueSetupExtend from "vite-plugin-vue-setup-extend";

import setupPlugins from "./vite/plugins";
import GlobalVarPlugin from "./vite/plugins/globalVar";

import { parseEnv } from "./vite/utils";

export default defineConfig(({ command, mode }) => {
	const isBuild = command == "build";
	console.log("isBuild", isBuild == true ? "当前是生产环境" : "当前是开发环境");
	const env = parseEnv(loadEnv(mode, process.cwd()));

	return {
		plugins: [
			vue(),
			GlobalVarPlugin(),
			// * 生成html模板
			createHtmlPlugin({
				inject: {
					data: {
						title: env.VITE_GLOB_APP_TITLE
					}
				}
			}),
			// * vue3 jsx语法支持
			vueJsx(),
			// * svg图标
			createSvgIconsPlugin({
				iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
				symbolId: "icon-[dir]-[name]",
				inject: "body-first",
				customDomId: "icon-svg"
			}),
			// * name 可以写在 script 标签上
			VueSetupExtend(),

			// * 是否生成包预览(分析依赖包大小,方便做优化处理)
			env.VITE_REPORT &&
				visualizer({
					open: true,
					gzipSize: true,
					brotliSize: true
				}),
			// * gzip compress
			env.VITE_BUILD_GZIP &&
				viteCompression({
					verbose: true,
					disable: false,
					threshold: 10240,
					algorithm: "gzip",
					ext: ".gz"
				}),
			...setupPlugins(isBuild, env)
		],
		esbuild: {
			// pure: env.VITE_DROP_CONSOLE ? ["console.log", "debugger"] : [],
		},
		resolve: {
			alias: {
				"@": fileURLToPath(new URL("./src", import.meta.url)),
				"@assets": fileURLToPath(new URL("./src/assets", import.meta.url)),
				"#": fileURLToPath(new URL("./types", import.meta.url)),
				"@CORE": fileURLToPath(new URL("./src/@CORE/", import.meta.url))
			}
		},

		base: isBuild ? "/" : "./",

		build: {
			outDir: "dist",
			minify: "esbuild",
			// 设置打包后的静态资源的引用路径
			assetsDir: "assets",
			// esbuild 打包更快，但是不能去除 console.log，terser打包慢，但能去除 console.log
			// minify: "terser",
			// terserOptions: {
			// 	compress: {
			// 		drop_console: viteEnv.VITE_DROP_CONSOLE,
			// 		drop_debugger: true
			// 	}
			// },
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
				output: {
					// Static resource classification and packaging
					chunkFileNames: "assets/js/[name]-[hash].js",
					entryFileNames: "assets/js/[name]-[hash].js",
					assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
					format: "es"
				}
			}
		},
		server: {
			host: "0.0.0.0",
			port: env.VITE_PORT,
			open: env.VITE_OPEN
		}
	};
});
